﻿using System.Web;
using System.Web.SessionState;

namespace RDIFramework.WebApp.Modules.handler
{
    using RDIFramework.ServiceAdapter;
    using RDIFramework.Utilities;
    using RDIFramework.WebCommon;

    /// <summary>
    /// PermissionHandler 的摘要说明
    /// </summary>
    public class PermissionHandler : IHttpHandler, IRequiresSessionState
    {
        // <summary> 
        /// 权限域编号(按权限管理范围来列出数据才可以，只能管理这个范围的数据)
        /// </summary>
        private string PermissionItemCodeManger = "Resource.ManagePermission";
        private string PermissionItemCodeAccess = "Resource.AccessPermission";

        private string action
        {
            get
            {
                return RDIFramework.WebCommon.PublicMethod.GetString(getObj("action"));
            }
        }

        private object getObj(string key) { return RDIFramework.WebCommon.StringHelper.GetRequestObject(key); }

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            switch (action)
            {
                case "GetModuleByUserId": //得到指定用户可以访问的模块
                    GetModuleByUserId(context);
                    break;
                case "GetModuleByRoleId": //得到指定角色可以访问的模块
                    GetModuleByRoleId(context);
                    break;
                case "GetPermissionItemsByUserId": //得到指定用户可以访问的操作权限项
                    GetPermissionItemsByUserId(context);
                    break;
                case "GetPermissionItemsByRoleId": //得到指定角色可以访问的操作权限项
                    GetPermissionItemsByRoleId(context);
                    break;
                case "GetPermissionScopeTargetIds": //得到指定用户可以访问的资源权限主键列表
                    GetPermissionScopeTargetIds(context);
                    break;
                case "GetUserRoleIds": //得到指定用户所拥有的角色主键列表
                    GetUserRoleIds(context);
                    break;
                case "GetRoleUserIds":  //获得角色中的用户主键
                    GetRoleUserIds(context);
                    break;
                case "SetUserModulePermission":  //设置用户模块权限（授予或回收）
                    SetUserModulePermission(context);
                    break;
                case "SetRoleModulePermission":  //设置角色模块权限（授予或回收）
                    SetRoleModulePermission(context);
                    break;
                case "SetUserPermissionItem":  //设置用户操作权限项权限（授予或回收）
                    SetUserPermissionItem(context);
                    break;
                case "SetRolePermissionItem":  // 设置角色操作权限项权限（授予或回收）
                    SetRolePermissionItem(context);
                    break;
                case "GrantRevokePermissionScopeTargets": //授予或回收资源的权限范围
                    GrantRevokePermissionScopeTargets(context);
                    break;
                case "RemoveUserFromRole":  //批量移除角色
                    RemoveUserFromRole(context);
                    break;
                case "AddUserToRole": //批量增加用户到角色
                    AddUserToRole(context);
                    break;
                case "RemoveRoleUser"://批量移除当前角色指定的用户
                    RemoveRoleUser(context); 
                    break;
                case "AddRoleUser": //批量添加指定的用户到当前角色
                    AddRoleUser(context);
                    break;
            }
        }

        /// <summary>
        /// 得到指定用户可以访问的模块
        /// </summary>
        /// <param name="ctx"></param>
        private void GetModuleByUserId(HttpContext ctx)
        {
            string userId = PublicMethod.GetString(getObj("userid"));
            string[] moduleIds = RDIFrameworkService.Instance.PermissionService.GetScopeModuleIdsByUserId(Utils.UserInfo, userId, "Resource.AccessPermission");
            ctx.Response.Write(this.GetSpitString(moduleIds));
        }

        /// <summary>
        /// 得到指定角色可以访问的模块
        /// </summary>
        /// <param name="ctx"></param>
        private void GetModuleByRoleId(HttpContext ctx)
        {
            string roleId = PublicMethod.GetString(getObj("roleid"));
            string[] moduleIds = RDIFrameworkService.Instance.PermissionService.GetScopeModuleIdsByRoleId(Utils.UserInfo, roleId, "Resource.AccessPermission");
            ctx.Response.Write(this.GetSpitString(moduleIds));
        }

        /// <summary>
        /// 得到指定用户可以访问的操作权限项
        /// </summary>
        /// <param name="ctx"></param>
        private void GetPermissionItemsByUserId(HttpContext ctx)
        {
            string userId = PublicMethod.GetString(getObj("userid"));
            string[] Ids = RDIFrameworkService.Instance.PermissionService.GetUserPermissionItemIds(Utils.UserInfo, userId);
            ctx.Response.Write(this.GetSpitString(Ids));
        }

        /// <summary>
        /// 得到指定角色可以访问的操作权限项
        /// </summary>
        /// <param name="ctx"></param>
        private void GetPermissionItemsByRoleId(HttpContext ctx)
        {
            string roleId = PublicMethod.GetString(getObj("roleid"));
            string[] Ids = RDIFrameworkService.Instance.PermissionService.GetRolePermissionItemIds(Utils.UserInfo, roleId);
            ctx.Response.Write(this.GetSpitString(Ids));
        }

        /// <summary>
        /// 获取资源权限范围主键数组
        /// </summary>
        /// <param name="ctx"></param>
        private void GetPermissionScopeTargetIds(HttpContext ctx)
        {
            string resourceCategory = PublicMethod.GetString(getObj("resourceCategory")); //资源分类
            string resourceId = PublicMethod.GetString(getObj("resourceId")); //资源主键
            string targetCategory = PublicMethod.GetString(getObj("targetCategory")); //目标类别
            string[] Ids = RDIFrameworkService.Instance.PermissionService.GetPermissionScopeTargetIds(Utils.UserInfo, resourceCategory, resourceId, targetCategory, this.PermissionItemCodeManger);
            ctx.Response.Write(this.GetSpitString(Ids));
        }

        /// <summary>
        /// 得到指定用户所拥有的角色主键列表
        /// </summary>
        /// <param name="ctx"></param>
        private void GetUserRoleIds(HttpContext ctx)
        {
            string userId = PublicMethod.GetString(getObj("userid"));
            string[] Ids = RDIFrameworkService.Instance.UserService.GetUserRoleIds(Utils.UserInfo,userId);
            ctx.Response.Write(this.GetSpitString(Ids));
        }

        /// <summary>
        /// 获得角色中的用户主键
        /// </summary>
        /// <param name="ctx"></param>
        private void GetRoleUserIds(HttpContext ctx)
        {
            string roleId = PublicMethod.GetString(getObj("roleId"));
            string[] userIds = RDIFrameworkService.Instance.RoleService.GetRoleUserIds(Utils.UserInfo, roleId);
            ctx.Response.Write(this.GetSpitString(userIds));
        }

        #region private void GrantRevokePermissionScopeTargets(HttpContext ctx) 授予或回收资源的权限范围
        /// <summary>
        /// 授予或回收资源的权限范围
        /// </summary>
        /// <param name="ctx"></param>
        private void GrantRevokePermissionScopeTargets(HttpContext ctx)
        {
            string resourceCategory = PublicMethod.GetString(getObj("resourceCategory")); //资源分类
            string resourceId = PublicMethod.GetString(getObj("resourceId")); //资源主键
            string targetCategory = PublicMethod.GetString(getObj("targetCategory")); //目标类别
            string grantTargetIds = PublicMethod.GetString(getObj("grantTargetIds")); //授予目标主键数组
            string revokeTargetIds = PublicMethod.GetString(getObj("revokeTargetIds")); //回收的目标主键数组
            string permissionItemId = RDIFrameworkService.Instance.PermissionItemService.GetEntityByCode(Utils.UserInfo, this.PermissionItemCodeManger).Id.ToString();
            if (string.IsNullOrEmpty(resourceId))
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = "请选择相应的资源！" }.ToString());
                return;
            }
            int successFlag = 0;

            if (!string.IsNullOrEmpty(grantTargetIds.Trim()))
            {
                if (!string.IsNullOrEmpty(grantTargetIds))
                {
                    string[] arrayGrantIds = RDIFramework.Utilities.StringHelper.RemoveFinalComma(grantTargetIds).TrimEnd(new char[] { ',' }).Split(',');
                    successFlag += RDIFrameworkService.Instance.PermissionService.GrantPermissionScopeTargets(Utils.UserInfo, resourceCategory, resourceId, targetCategory, arrayGrantIds, permissionItemId);
                }
            }
            
            if (!string.IsNullOrEmpty(revokeTargetIds.Trim()))
            {
                string[] arrayRevokeIds = RDIFramework.Utilities.StringHelper.RemoveFinalComma(revokeTargetIds).TrimEnd(new char[] { ',' }).Split(',');
                successFlag += RDIFrameworkService.Instance.PermissionService.RevokePermissionScopeTargets(Utils.UserInfo, resourceCategory, resourceId, targetCategory, arrayRevokeIds, permissionItemId);
            }

            if (successFlag > 0)
            {
                successFlag = 1;
                ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = "操作成功！" }.ToString());
            }
            else
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = "操作失败！" }.ToString());
            }
        }
        #endregion

        #region private void SetUserModulePermission(HttpContext ctx) 设置用户模块权限（授予或回收）
        /// <summary>
        /// 设置用户模块权限（授予或回收）
        /// </summary>
        /// <param name="ctx"></param>
        private void SetUserModulePermission(HttpContext ctx)
        {
            string userId = PublicMethod.GetString(getObj("userid"));
            string grantModuleIds = PublicMethod.GetString(getObj("grantIds"));
            string revokeModuleids = PublicMethod.GetString(getObj("revokeIds"));
            UserInfo vUser = Utils.UserInfo;

            if (string.IsNullOrEmpty(userId))
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = "请选择相应的用户！"}.ToString());
                return;
            }
            int successFlag = 0;
            if (!string.IsNullOrEmpty(grantModuleIds))
            {
                string[] grantIds = grantModuleIds.TrimEnd(new char[] { ',' }).Split(',');
                if (grantIds.Length > 0)
                {
                    successFlag += RDIFrameworkService.Instance.PermissionService.GrantUserModuleScope(vUser, userId, this.PermissionItemCodeAccess, grantIds);
                }
                else 
                {
                    successFlag = 1;
                }
            }

            if (!string.IsNullOrEmpty(revokeModuleids))
            {
                string[] revokeIds = revokeModuleids.TrimEnd(new char[] { ',' }).Split(',');
                if (revokeIds.Length > 0)
                {
                    successFlag += RDIFrameworkService.Instance.PermissionService.RevokeUserModuleScope(vUser, userId, this.PermissionItemCodeAccess, revokeIds);
                }
                else
                {
                    successFlag = 1;
                }
            }

            if (successFlag > 0)
            {
                successFlag = 1;
                ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = "操作成功！" }.ToString());
            }
            else
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = "操作失败！" }.ToString());
            }
        }
        #endregion

        #region private void SetRoleModulePermission(HttpContext ctx) 设置角色模块权限（授予或回收）
        /// <summary>
        /// 设置角色模块权限（授予或回收）
        /// </summary>
        /// <param name="ctx"></param>
        private void SetRoleModulePermission(HttpContext ctx)
        {
            string roleId = PublicMethod.GetString(getObj("roleid"));
            string grantModuleIds = PublicMethod.GetString(getObj("grantIds"));
            string revokeModuleids = PublicMethod.GetString(getObj("revokeIds"));
            UserInfo vUser = Utils.UserInfo;

            if (string.IsNullOrEmpty(roleId))
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = "请选择相应的角色！" }.ToString());
                return;
            }
            int successFlag = 0;
            if (!string.IsNullOrEmpty(grantModuleIds))
            {
                string[] grantIds = grantModuleIds.TrimEnd(new char[] { ',' }).Split(',');
                if (grantIds.Length > 0)
                {
                    successFlag += RDIFrameworkService.Instance.PermissionService.GrantRoleModuleScope(vUser, roleId, this.PermissionItemCodeAccess, grantIds);
                }
                else
                {
                    successFlag = 1;
                }
            }

            if (!string.IsNullOrEmpty(revokeModuleids))
            {
                string[] revokeIds = revokeModuleids.TrimEnd(new char[] { ',' }).Split(',');
                if (revokeIds.Length > 0)
                {
                    successFlag += RDIFrameworkService.Instance.PermissionService.RevokeRoleModuleScope(vUser, roleId, this.PermissionItemCodeAccess, revokeIds);
                }
                else
                {
                    successFlag = 1;
                }
            }

            if (successFlag > 0)
            {
                successFlag = 1;
                ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = "操作成功！" }.ToString());
            }
            else
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = "操作失败！" }.ToString());
            }
        }
        #endregion

        #region private void SetUserPermissionItem(HttpContext ctx) 设置用户操作权限项权限（授予或回收）
        /// <summary>
        /// 设置用户操作权限项权限（授予或回收）
        /// </summary>
        /// <param name="ctx"></param>
        private void SetUserPermissionItem(HttpContext ctx)
        {
            string userid = PublicMethod.GetString(getObj("userid"));
            string grantIds = PublicMethod.GetString(getObj("grantIds"));
            string revokeIds = PublicMethod.GetString(getObj("revokeIds"));
            UserInfo vUser = Utils.UserInfo;

            if (string.IsNullOrEmpty(userid))
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = "请选择相应的用户！" }.ToString());
                return;
            }
            int successFlag = 0;
            if (!string.IsNullOrEmpty(grantIds))
            {
                string[] arrayGrantIds = grantIds.TrimEnd(new char[] { ',' }).Split(',');
                if (arrayGrantIds.Length > 0)
                {
                    successFlag += RDIFrameworkService.Instance.PermissionService.GrantUserPermissions(vUser, new string[] { userid },arrayGrantIds);
                }
                else
                {
                    successFlag = 1;
                }
            }

            if (!string.IsNullOrEmpty(revokeIds))
            {
                string[] arrayRevokeIds = revokeIds.TrimEnd(new char[] { ',' }).Split(',');
                if (arrayRevokeIds.Length > 0)
                {
                    successFlag += RDIFrameworkService.Instance.PermissionService.RevokeUserPermissions(vUser, new string[] { userid }, arrayRevokeIds);
                }
                else
                {
                    successFlag = 1;
                }
            }

            if (successFlag > 0)
            {
                successFlag = 1;
                ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = "操作成功！" }.ToString());
            }
            else
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = "操作失败！" }.ToString());
            }
        }
        #endregion

        #region private void SetRolePermissionItem(HttpContext ctx) 设置角色操作权限项权限（授予或回收）
        /// <summary>
        /// 设置角色操作权限项权限（授予或回收）
        /// </summary>
        /// <param name="ctx"></param>
        private void SetRolePermissionItem(HttpContext ctx)
        {
            string roleId = PublicMethod.GetString(getObj("roleid"));
            string grantIds = PublicMethod.GetString(getObj("grantIds"));
            string revokeIds = PublicMethod.GetString(getObj("revokeIds"));
            UserInfo vUser = Utils.UserInfo;

            if (string.IsNullOrEmpty(roleId))
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = "请选择相应的角色！" }.ToString());
                return;
            }
            int successFlag = 0;
            if (!string.IsNullOrEmpty(grantIds))
            {
                string[] arrayGrantIds = grantIds.TrimEnd(new char[] { ',' }).Split(',');
                if (arrayGrantIds.Length > 0)
                {
                    successFlag += RDIFrameworkService.Instance.PermissionService.GrantRolePermissions(vUser, new string[]{ roleId }, arrayGrantIds);
                }
                else
                {
                    successFlag = 1;
                }
            }

            if (!string.IsNullOrEmpty(revokeIds))
            {
                string[] arrayRevokeIds = revokeIds.TrimEnd(new char[] { ',' }).Split(',');
                if (arrayRevokeIds.Length > 0)
                {
                    successFlag += RDIFrameworkService.Instance.PermissionService.RevokeRolePermissions(vUser, new string[] { roleId }, arrayRevokeIds);
                }
                else
                {
                    successFlag = 1;
                }
            }

            if (successFlag > 0)
            {
                successFlag = 1;
                ctx.Response.Write(new JsonMessage { Success = true, Data = successFlag.ToString(), Message = "操作成功！" }.ToString());
            }
            else
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = successFlag.ToString(), Message = "操作失败！" }.ToString());
            }
        }
        #endregion

        #region 增加或移除用户到角色（UserService）
        /// <summary>
        /// 批量移除角色
        /// </summary>
        /// <param name="ctx"></param>
        private void RemoveUserFromRole(HttpContext ctx)
        {
            string userId = PublicMethod.GetString(getObj("userid"));
            string targetIds = PublicMethod.GetString(getObj("targetIds"));
            int returnValue =  RDIFrameworkService.Instance.UserService.RemoveUserFromRole(Utils.UserInfo, userId,targetIds.TrimEnd(new char[] { ',' }).Split(','));
            if (returnValue > 0)
            { 
                ctx.Response.Write(new JsonMessage { Success = true, Data = "1", Message = "操作成功！" }.ToString());
            }
            else
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = "操作失败！" }.ToString());
            }
        }

        /// <summary>
        /// 批量增加用户到角色
        /// </summary>
        /// <param name="ctx"></param>
        private void AddUserToRole(HttpContext ctx)
        {
            string userId = PublicMethod.GetString(getObj("userid"));
            string targetIds = PublicMethod.GetString(getObj("targetIds"));
            int returnValue = RDIFrameworkService.Instance.UserService.AddUserToRole(Utils.UserInfo, userId, targetIds.TrimEnd(new char[] { ',' }).Split(','));
            if (returnValue > 0)
            {
                ctx.Response.Write(new JsonMessage { Success = true, Data = "1", Message = "操作成功！" }.ToString());
            }
            else
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = "操作失败！" }.ToString());
            }
        }
        #endregion

        #region 批量添加或移除指定角色的用户（RoleService）
        /// <summary>
        /// 批量添加指定的用户到当前角色
        /// </summary>
        /// <param name="ctx"></param>
        private void AddRoleUser(HttpContext ctx)
        {
            string roleId = PublicMethod.GetString(getObj("roleId"));
            string targetIds = PublicMethod.GetString(getObj("targetIds"));
            int returnValue = RDIFrameworkService.Instance.RoleService.AddUserToRole(Utils.UserInfo, roleId, targetIds.TrimEnd(new char[] { ',' }).Split(','));
            if (returnValue > 0)
            { 
                ctx.Response.Write(new JsonMessage { Success = true, Data = "1", Message = "操作成功！" }.ToString());
            }
            else
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = "操作失败！" }.ToString());
            }
        }

        /// <summary>
        /// 批量移除当前角色指定的用户
        /// </summary>
        /// <param name="ctx"></param>
        private void RemoveRoleUser(HttpContext ctx)
        {
            string roleId = PublicMethod.GetString(getObj("roleId"));
            string targetIds = PublicMethod.GetString(getObj("targetIds"));
            int returnValue = RDIFrameworkService.Instance.RoleService.RemoveUserFromRole(Utils.UserInfo, roleId, targetIds.TrimEnd(new char[] { ',' }).Split(','));
            if (returnValue > 0)
            {
                ctx.Response.Write(new JsonMessage { Success = true, Data = "1", Message = "操作成功！" }.ToString());
            }
            else
            {
                ctx.Response.Write(new JsonMessage { Success = false, Data = "0", Message = "操作失败！" }.ToString());
            }
        }
        #endregion

        private string GetSpitString(string[] sArrary)
        {
            string returnValue = "";
            if (sArrary != null && sArrary.Length > 0)
            {
                foreach (string value in sArrary)
                {
                    returnValue += value + ",";
                }
              returnValue = returnValue.Remove(returnValue.Length - 1, 1);
            }

            return returnValue;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}